package com.yangguang.utils;

import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件操作工具类
 */
public class FileUtil {

	/**
	 * 读取文件内容为二进制数组
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] read2ByteArray(String filePath) throws IOException {

		InputStream in = new FileInputStream(filePath);
		byte[] data = inputStream2ByteArray(in);
		in.close();

		return data;
	}

	/**
	 * 流转二进制数组
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] inputStream2ByteArray(InputStream in) throws IOException {

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}

	public static String bufferedImageToBase64Image(BufferedImage image,String lastDir){
		String bodyParam=null;
		try{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ImageIO.write(image,lastDir,out);
			byte[] bytes = out.toByteArray();
			System.out.println(bytes.length);
			String imageBase64 = new String(Base64.encodeBase64(bytes), "UTF-8");
			bodyParam = "image=" + imageBase64;
		}catch (Exception e){
			e.printStackTrace();
		}
		return bodyParam;
	}
}
